package com.yuan.fruitweb.web;

import com.yuan.fruitweb.model.Fruit;
import com.yuan.fruitweb.service.FruitService;
import com.yuan.fruitweb.service.impl.FruitServiceImpl;
import lombok.SneakyThrows;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author YuanYuemeng
 * @date 2020/11/22
 */
//@WebServlet("/fruitEdit")
public class FruitEditservlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //拿到对应id的水果信息，显示到编辑页面
        String strId = req.getParameter("id");
        int id = Integer.parseInt(strId);


        ApplicationContext applicationContext = (ApplicationContext) getServletContext().getAttribute("applicationContext");
        FruitService fruitService = applicationContext.getBean("fruitService",FruitService.class);
        Fruit fruit = fruitService.findFruitById(id);
        req.setAttribute("fruit",fruit);
        //木有错误
        req.getRequestDispatcher("fruitEdit.jsp").forward(req,resp);
    }

    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取用户输入，保存到数据
        Fruit fruit = new Fruit();
        BeanUtils.populate(fruit,req.getParameterMap());


        ApplicationContext applicationContext = (ApplicationContext) getServletContext().getAttribute("applicationContext");
        FruitService fruitService = applicationContext.getBean("fruitService",FruitService.class);
        boolean ret = fruitService.updateFruit(fruit);
        if(ret){
            resp.sendRedirect("fruitList");
        }else{
            req.getRequestDispatcher("fruitEdit.jsp").forward(req,resp);
        }
    }

}